package com.ts.manage.course.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ts.framework.domain.cms.CmsPage;
import com.ts.framework.domain.cms.response.CmsPageResult;
import com.ts.framework.domain.cms.response.CmsPostPageResult;
import com.ts.framework.domain.cms.response.CoursePreviewResult;
import com.ts.framework.domain.course.CourseBase;
import com.ts.framework.domain.course.CourseMarket;
import com.ts.framework.domain.course.CoursePic;
import com.ts.framework.domain.course.CoursePub;
import com.ts.framework.domain.course.ext.CourseInfo;
import com.ts.framework.domain.course.ext.CourseView;
import com.ts.framework.domain.course.ext.TeachplanNode;
import com.ts.framework.domain.course.request.CourseListRequest;
import com.ts.framework.domain.course.response.AddCourseResult;
import com.ts.framework.domain.course.response.CourseCode;
import com.ts.framework.domain.course.response.CoursePublishResult;
import com.ts.framework.exception.ExceptionCast;
import com.ts.framework.model.response.CommonCode;
import com.ts.framework.model.response.QueryResponseResult;
import com.ts.framework.model.response.QueryResult;
import com.ts.framework.model.response.ResponseResult;
import com.ts.manage.course.client.CmsPageClient;
import com.ts.manage.course.dao.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 课程管理服务层
 */
@Service
@Slf4j
public class CourseService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    TeachplanRepository teachplanRepository;
    @Autowired
    CourseMarketRepository courseMarketRepository;
    @Autowired
    CoursePicRepository coursePicRepository;
    @Autowired
    CoursePubRepository coursePubRepository;
    @Autowired
    TeachPlanService teachPlanService;
    @Autowired
    CmsPageClient cmsPageClient;
    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;

    //分页查询课程列表
    public QueryResponseResult findCourseListByPage(int page, int size, CourseListRequest courseListRequest) {
        if (page <= 0) {
            page = 0;
        }
        if (size <= 0) {
            size = 10;
        }
        if (courseListRequest == null) {
            courseListRequest = new CourseListRequest();
        }
        //设置分页参数
        PageHelper.startPage(page, size);
        //分页查询
        Page<CourseInfo> courseList = courseMapper.findCourseListByPage(courseListRequest);
        //查询列表
        List<CourseInfo> result = courseList.getResult();
        //总记录数
        long total = courseList.getTotal();
        //查询结果集
        QueryResult<CourseInfo> courseInfoQueryResult = new QueryResult<>();
        courseInfoQueryResult.setList(result);
        courseInfoQueryResult.setTotal(total);
        return new QueryResponseResult(CommonCode.SUCCESS, courseInfoQueryResult);
    }

    //添加课程信息
    @Transactional
    public AddCourseResult addCourseBase(CourseBase courseBase) {
        courseBase.setStatus("202001");//课程状态默认未发布  202002已发布
        courseBaseRepository.save(courseBase);
        return new AddCourseResult(CommonCode.SUCCESS, courseBase.getId());
    }

    //查询课程基础信息
    public CourseBase findCourseBaseById(String courseId) {
        Optional<CourseBase> optional = courseBaseRepository.findById(courseId);
        if (!optional.isPresent()) {
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        CourseBase courseBase = optional.get();
        return courseBase;
    }

    //更新课程基础信息
    @Transactional
    public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        CourseBase courseBaseDB = this.findCourseBaseById(id);
        if (courseBaseDB == null) {
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        //修改课程信息
        courseBaseDB.setName(courseBase.getName());
        courseBaseDB.setMt(courseBase.getMt());
        courseBaseDB.setSt(courseBase.getSt());
        courseBaseDB.setGrade(courseBase.getGrade());
        courseBaseDB.setStudymodel(courseBase.getStudymodel());
        courseBaseDB.setUsers(courseBase.getUsers());
        courseBaseDB.setDescription(courseBase.getDescription());
        courseBaseRepository.save(courseBaseDB);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //获取课程营销信息
    public CourseMarket getCourseMarketById(String courseId) {
        Optional<CourseMarket> optional = courseMarketRepository.findById(courseId);
        if (!optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    //更新课程营销信息
    @Transactional
    public CourseMarket updateCourseMarket(String id, CourseMarket courseMarket) {
        CourseMarket one = this.getCourseMarketById(id);
        if (one != null) {
            one.setCharge(courseMarket.getCharge());
            one.setStartTime(courseMarket.getStartTime());//课程有效期，开始时间
            one.setEndTime(courseMarket.getEndTime());//课程有效期，结束时间
            one.setPrice(courseMarket.getPrice());
            one.setQq(courseMarket.getQq());
            one.setValid(courseMarket.getValid());
            courseMarketRepository.save(one);
        } else {
            //添加课程营销信息
            one = new CourseMarket();
            BeanUtils.copyProperties(courseMarket, one);
            //设置课程id
            one.setId(id);
            courseMarketRepository.save(one);
        }
        return one;
    }

    //添加课程图片
    @Transactional
    public ResponseResult addCoursePic(String courseId, String pic) {
        if (StringUtils.isEmpty(courseId) || StringUtils.isEmpty(pic)) {
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //获取课程图片
    public CoursePic findCoursePic(String courseId) {
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (!optional.isPresent()) {
            ExceptionCast.cast(CommonCode.INIT_PARAM);
        }
        return optional.get();
    }

    //删除课程图片
    @Transactional
    public ResponseResult delCoursePic(String courseId) {
        Integer count = coursePicRepository.deleteCoursePicByCourseid(courseId);
        if (count > 0) {
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    //查询课程详情页面模型数据
    public CourseView getCourseView(String courseId) {
        CourseView courseView = new CourseView();
        //查询课程基本信息
        Optional<CourseBase> baseOptional = courseBaseRepository.findById(courseId);
        if (baseOptional.isPresent()) {
            CourseBase courseBase = baseOptional.get();
            courseView.setCourseBase(courseBase);
        }
        //查询课程营销信息
        Optional<CourseMarket> marketOptional = courseMarketRepository.findById(courseId);
        if (marketOptional.isPresent()) {
            CourseMarket courseMarket = marketOptional.get();
            courseView.setCourseMarket(courseMarket);
        }
        //查询课程图片信息
        Optional<CoursePic> picOptional = coursePicRepository.findById(courseId);
        if (picOptional.isPresent()) {
            CoursePic coursePic = picOptional.get();
            courseView.setCoursePic(coursePic);
        }
        //查询课程计划信息
        TeachplanNode teachplanNode = teachplanMapper.selectAllPlan(courseId);
        courseView.setTeachplanNode(teachplanNode);
        return courseView;
    }


    //课程详情预览-返回url
    public CoursePreviewResult coursePreview(String id) {
        CmsPage cmsPage = this.makeCmsPage(id);
        //远程调用Cms服务,保存CmsPage
        CmsPageResult cmsPageResult = cmsPageClient.saveCmsPage(cmsPage);
        if (!cmsPageResult.isSuccess()) {
            return new CoursePreviewResult(CommonCode.FAIL, null);
        }
        //拼接预览课程详情的url
        String pageId = cmsPageResult.getCmsPage().getPageId();
        String pageUrl = previewUrl + pageId;
        return new CoursePreviewResult(CommonCode.SUCCESS, pageUrl);
    }

    //课程发布
    @Transactional
    public CoursePublishResult coursePublish(String id) {
        CmsPage cmsPage = this.makeCmsPage(id);
        //远程调用Cms服务,保存CmsPage
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        //如果课程发布成功,更新课程状态
        if (!cmsPostPageResult.isSuccess()) {
            return new CoursePublishResult(CommonCode.FAIL, null);
        }
        CourseBase courseBase = this.findCourseBaseById(id);
        courseBase.setStatus("202002");
        courseBaseRepository.save(courseBase);
        //课程信息保存更新到coursePub表中
        CoursePub coursePub = this.createCoursePub(id);
        this.saveCoursePub(id, coursePub);
        //保存课程计划媒资信息到待索引表
        teachPlanService.saveTeachplanMediaPub(id);
        //页面url
        String pageUrl = cmsPostPageResult.getPageUrl();
        return new CoursePublishResult(CommonCode.SUCCESS, pageUrl);
    }

    public CoursePub saveCoursePub(String courseId, CoursePub coursePub) {
        //coursePub.setId(courseId);
        if (StringUtils.isNotEmpty(courseId)) {
            ExceptionCast.cast(CourseCode.COURSE_PUBLISH_PERVIEWISNULL);
        }
        CoursePub coursePubNew = null;
        Optional<CoursePub> optional = coursePubRepository.findById(courseId);
        if (optional.isPresent()) {
            coursePubNew = optional.get();
        }
        if (coursePubNew == null) {
            coursePubNew = new CoursePub();
        }
        BeanUtils.copyProperties(coursePub, coursePubNew);
        //设置主键
        coursePubNew.setId(courseId);
        //更新时间戳为最新时间
        coursePub.setTimestamp(new Date());
        //发布时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        coursePub.setPubTime(date);
        coursePubRepository.save(coursePub);
        return coursePub;
    }

    //根据id获取cms页面
    private CmsPage makeCmsPage(String id) {
        //根据课程Id获取课程基本信息
        CourseBase courseBase = findCourseBaseById(id);
        //创建CmsPage对象,并设置属性
        CmsPage cmsPage = new CmsPage();
        cmsPage.setDataUrl(publish_dataUrlPre + id);
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setTemplateId(publish_templateId);
        cmsPage.setSiteId(publish_siteId);
//        cmsPage.setPageCreateTime(new Date());
        cmsPage.setPageName(id + ".html");
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);
        cmsPage.setPageWebPath(publish_page_webpath);
        return cmsPage;
    }

    //拼装CoursePub对象
    private CoursePub createCoursePub(String courseId) {
        CoursePub coursePub = new CoursePub();
        coursePub.setId(courseId);
        //设置课程基础信息
        Optional<CourseBase> optionalCourseBase = courseBaseRepository.findById(courseId);
        if (optionalCourseBase.isPresent()) {
            CourseBase courseBase = optionalCourseBase.get();
            BeanUtils.copyProperties(courseBase, coursePub);
        }
        //设置课程营销信息
        Optional<CourseMarket> optionalCourseMarket = courseMarketRepository.findById(courseId);
        if (optionalCourseMarket.isPresent()) {
            CourseMarket courseMarket = optionalCourseMarket.get();
            BeanUtils.copyProperties(courseMarket, coursePub);
        }
        //设置课程图片信息
        Optional<CoursePic> optionalCoursePic = coursePicRepository.findById(courseId);
        if (optionalCoursePic.isPresent()) {
            CoursePic coursePic = optionalCoursePic.get();
            BeanUtils.copyProperties(coursePic, coursePub);
        }
        TeachplanNode teachplanNode = teachplanMapper.selectAllPlan(courseId);
        String jsonTeachPlan = JSON.toJSONString(teachplanNode);
        coursePub.setTeachplan(jsonTeachPlan);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy--MM--dd HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        coursePub.setPubTime(dateString);
        coursePub.setTimestamp(new Date());
        return coursePub;
    }
}
